﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Windows.Input;
using SqlMiM.Common.ViewModel;
using SqlMiM.Common.Commands;
using System.Collections.ObjectModel;
using System.Diagnostics;
using SqlMiM.SqlServer.Core;
using System.Windows.Threading;
using System.Collections;
using System.Windows;
using MvvmFoundation.Wpf;

namespace SqlMiM.SqlServer.Server2008
{
    public class ViewModel : ObservableObject
    {
        private enum ADO_Net_Performance_Counters
        {
            NumberOfActiveConnectionPools,
            NumberOfReclaimedConnections,
            HardConnectsPerSecond,
            HardDisconnectsPerSecond,
            NumberOfActiveConnectionPoolGroups,
            NumberOfInactiveConnectionPoolGroups,
            NumberOfInactiveConnectionPools,
            NumberOfNonPooledConnections,
            NumberOfPooledConnections,
            NumberOfStasisConnections
            // The following performance counters are more expensive to track.
            // Enable ConnectionPoolPerformanceCounterDetail in your config file.
            //     SoftConnectsPerSecond
            //     SoftDisconnectsPerSecond
            //     NumberOfActiveConnections
            //     NumberOfFreeConnections
        }

        private PerformanceCounter[] perfCounters = new PerformanceCounter[10];
        private ObservableCollection<ConnectionStat> userConnections;
        private Queue internalUserConnectionsQueue;
        private BackgroundWorker workerGetPerfs;
        private DispatcherTimer timer;
        private int totalInterval;
        private int maxConnections;

        public int MaxConnections
        {
            get { return maxConnections; }
            set
            {
                maxConnections = value;
                this.RaisePropertyChanged("MaxConnections");
            }
        }

        private void SetUpPerformanceCounters()
        {
            this.perfCounters = new PerformanceCounter[1];
            ////string instanceName = GetInstanceName();
            //Type apc = typeof(ADO_Net_Performance_Counters);
            //int i = 0;
            //foreach (string s in Enum.GetNames(apc))
            //{
            //    this.perfCounters[i] = new PerformanceCounter();
            //    this.perfCounters[i].CategoryName = ".NET Data Provider for SqlServer";
            //    this.perfCounters[i].CounterName = s;
            //    this.perfCounters[i].InstanceName = "*";
            //    i++;
            //}
            this.perfCounters[0] = new PerformanceCounter("MSSQL$SQL2008:General Statistics", "User Connections");
        }



        public int TotalInterval
        {
            get { return totalInterval; }
            set
            {
                totalInterval = value; this.RaisePropertyChanged("TotalInterval");
            }
        }


        public ObservableCollection<ConnectionStat> UserConnections
        {
            get { return userConnections; }
            set
            {
                userConnections = value;
                this.RaisePropertyChanged("UserConnections");
            }
        }

        public ViewModel()
        {
            this.TotalInterval = 60;
            this.MaxConnections = 100;
            
            this.UserConnections = new ObservableCollection<ConnectionStat>();

            BackgroundWorker bw = new BackgroundWorker();

            bw.DoWork += (sender , args) => { this.SetUpPerformanceCounters(); };
           
            bw.RunWorkerCompleted += (sender, args) =>
            {
                this.timer = new DispatcherTimer(TimeSpan.FromSeconds(10d), DispatcherPriority.Background, new EventHandler(GetPerfs_DoWork), Dispatcher.CurrentDispatcher);
            };

            bw.RunWorkerAsync();
        }


        private void workerGetPerfs_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {

        }

        private void GetPerfs_DoWork(object sender, EventArgs e)
        {
            if (this.perfCounters == null || this.perfCounters.Length == 0)
                return;

            foreach (PerformanceCounter p in this.perfCounters)
            {
                if (p.CounterName == "User Connections")
                {
                    var time = DateTime.Now.Second;
                    var number = (int)p.NextValue();

                    var stat = (from c in this.UserConnections
                               where c.Time == time
                               select c).FirstOrDefault();
                    
                    if (stat == null)
                        this.UserConnections.Add(new ConnectionStat() { Number = number, Time = time });
                    else
                        stat.Number = number;

                    //this.UserConnections = new ObservableCollection<ConnectionStat>(t);

                }
            }

        }



    }



}
